#! /usr/bin/env bash

set -e

PROJECT_DIR=`pwd`

build_playform() {
    rm -rf ${PROJECT_DIR}/output
    rm -rf ${PROJECT_DIR}/build
    
    mkdir ${PROJECT_DIR}/build
    pushd ${PROJECT_DIR}/build

    if [ "$1" = "Android" ]; then
        echo "build for android"
        cmake .. -DCMAKE_SYSTEM_NAME=Android -DCMAKE_ANDROID_ARCH_ABI=$2 -DCMAKE_SYSTEM_VERSION=21 -DCMAKE_BUILD_TYPE="$CONFIG"
    elif [ "$1" = "iOS" ]; then
        if [ "$2" = "os" ]; then
            echo "build for ios device"
            arch="arm64"
            version=`xcodebuild -version|awk 'NR== 1 {print $2}'`
            echo "xcode version:$version"
            if [ $version \< "14" ]; then
                echo "version less than 14"
                arch="armv7 arm64"
            fi
            cmake .. -DCMAKE_TOOLCHAIN_FILE=tools/cmake/ios.toolchain.cmake -G Xcode -DPLATFORM=OS -DCMAKE_SYSTEM_NAME=iOS -DDEPLOYMENT_TARGET=9 -DARCHS="$arch" -DCMAKE_BUILD_TYPE="$CONFIG"
        elif [ "$2" = "sim" ]; then
            echo "build for ios simulator"
            cmake .. -DCMAKE_TOOLCHAIN_FILE=tools/cmake/ios.toolchain.cmake -G Xcode -DPLATFORM=SIMULATOR64 -DCMAKE_SYSTEM_NAME=iOS -DCMAKE_BUILD_TYPE="$CONFIG"
        fi
    fi

    cmake --build . --config "$CONFIG"
    cmake --install .
}

build_android() {
    build_playform Android arm64-v8a
    build_playform Android armeabi-v7a
}

build_ios() {
    build_playform iOS os
    build_playform iOS sim
    FMK_NAME='mydecoder'
    DEVICE_DIR=${PROJECT_DIR}/output/ios/os/${FMK_NAME}.framework
    SIMULATOR_DIR=${PROJECT_DIR}/output/ios/sim/${FMK_NAME}.framework
    INSTALL_DIR=${PROJECT_DIR}/output/ios/fat/${FMK_NAME}.framework
    echo "merge ios device and simulator framework"
    if [ -d "${INSTALL_DIR}" ]; then
        rm -rf ${INSTALL_DIR}
    fi

    mkdir -p ${PROJECT_DIR}/output/ios/fat/
    cp -LR ${DEVICE_DIR} ${INSTALL_DIR}
    lipo -create ${DEVICE_DIR}/${FMK_NAME} ${SIMULATOR_DIR}/${FMK_NAME} -output ${INSTALL_DIR}/${FMK_NAME}
}

print_help() {
    echo "usage sh build.sh <platform>(ios|android) [configuration](Release|Debug)"
    exit 0
}

PLATFORM=$1
CONFIG=$2

if [ -z "$CONFIG" ]; then
    CONFIG="Release"
fi

if [ $CONFIG != "Release" ] && [ $CONFIG != "Debug" ]; then
    print_help
fi

if [ "$PLATFORM" == "android" ]; then
    build_android
elif [ "$PLATFORM" == "ios" ]; then
    build_ios
else
    print_help
fi

echo "build mydecoder successfully"